package com.tanhua.commons.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class ImagesStreamUtils {

    public static File convertMultipartFiletoFile(MultipartFile multipartFile) throws IOException {

        String property = System.getProperty("java.io.tmpdir");
        String fileTmpPath = property + "/" + multipartFile.getOriginalFilename();
        File file = new File(fileTmpPath);
        System.out.println("fileTmpPath..." + fileTmpPath);
        multipartFile.transferTo(file);
        return file;
    }

    public static File InputStringToFile(InputStream inputStream) throws IOException {


        Path imageTmpPath = Paths.get("tanhua-app-server", "src", "main", "resources").resolve("tmp").resolve("tmp.jpg");
        Files.copy(inputStream, imageTmpPath, StandardCopyOption.REPLACE_EXISTING);

        File imageFile = imageTmpPath.toFile();
        System.out.println("图片文件已创建: " + imageFile.getAbsolutePath());
        System.out.println("文件大小: " + imageFile.length() + " bytes");


        // 定义图片保存路径
        Path imagePath = Paths.get("output.jpg"); // 根据实际图片类型修改扩展名

        // 将图片流写入文件
        Files.copy(inputStream, imagePath, StandardCopyOption.REPLACE_EXISTING);

        // 创建File对象
        File file = imagePath.toFile();
        return file;
    }
}
